package com.medvalley.tcm.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.medvalley.tcm.cache.RedisCache;
import com.medvalley.tcm.service.SMSService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class SMSServiceImpl implements SMSService, InitializingBean {

    private static Logger LOGGER = LoggerFactory.getLogger(SMSServiceImpl.class);
    @Autowired
    private RedisCache redisCache;
    private String accessKey = "LTAImEYCt3oofbDP";
    private String accessSecret = "YczQrsbzVHkm7RC7PyTCBkqnycFMN4";
    private IAcsClient acsClient;

    @Override
    public void sendSmsCode(String phone) throws ClientException {
        this.sendSms(phone, "SMS_140260050");
    }

    @Override
    public boolean validateCode(String phone, String smsCode) {
        String code = redisCache.getValue(phone);
        if (StringUtils.isEmpty(code)) {
            return false;
        }
        return code.equals(smsCode);
    }

    @Override
    public void sendSms(String phone, String template) throws ClientException {
        String code = "";
        double random = Math.random();
        int codeInt = (int) (random * 10000);
        if (codeInt < 1000) {
            codeInt = 1000 + codeInt;
        }
        code = String.valueOf(codeInt);
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers(phone);
        request.setSignName("慧医谷科技");
        request.setTemplateCode(template);
        request.setTemplateParam("{ \"code\":\"" + code + "\"}");
        request.setOutId(System.currentTimeMillis() + "");
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            LOGGER.info(" phone:{},code:{}", phone, code);
            redisCache.setValue(phone, code, 300);
        } else {
            LOGGER.error(" send sms code error, phone:{},code:{},errorcode:{},errorMsg:{}", phone, code,
                    sendSmsResponse.getCode(), sendSmsResponse.getMessage());
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKey, accessSecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        acsClient = new DefaultAcsClient(profile);
    }
}
